package com.itcs.netty.client;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;

import java.util.concurrent.TimeUnit;

/**
 * 重连检测狗，当发现当前的链路不稳定关闭之后，进行重连
 * 
 * @author LiuPeng
 * 
 */
@Sharable
public abstract class ConnectionWatchdog extends ChannelInboundHandlerAdapter implements TimerTask, ChannelHandlerHolder {

	private final NettyClientBootstrap bootstrap;
	private final Timer timer;
	private int attempts;

	public ConnectionWatchdog(NettyClientBootstrap bootstrap, Timer timer) {
		this.bootstrap = bootstrap;
		this.timer = timer;
	}

	/**
	 * channel链路每次active的时候，将其连接的次数重新? 0
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//System.out.println("连接服务器链路已经激活了，重连尝试次数重新置为0");
		attempts = 0;
		ctx.fireChannelActive();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		attempts++;
		// 重连的间隔时间会越来越长
		int timeout = attempts > 14 ? (1000 * 60) : (2 << attempts);
		System.out.println("与服务器链路关闭," + timeout + "毫秒后进行第 " + attempts + " 次重连...");
		timer.newTimeout(this, timeout, TimeUnit.MILLISECONDS);
		ctx.fireChannelInactive();
	}

	@Override
	public void run(Timeout timeout) throws Exception {
		bootstrap.connect(this);
	}

}